package cc.wanforme.authtest.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cc.wanforme.authtest.config.auth.HasPermission;

@Controller("/")
@RestController
public class TestController {

	@GetMapping("/login")
	public String login() {
		// 使用虚假的账号和权限登录，只要设置权限了就行
		String username = "test1";
		String password = "233";
		
		String permission = "testPermission"; // 一个权限
		String role = "ROLE_testRole"; // 一个角色
		
		List<SimpleGrantedAuthority> authorities = new ArrayList<>(2);
		authorities.add(new SimpleGrantedAuthority(permission));
		authorities.add(new SimpleGrantedAuthority(role));
		
		UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(username, password, authorities);
		SecurityContextHolder.getContext().setAuthentication(upat);
		
		return "Login success";
	}
	
	@GetMapping("/logout")
	public String logout() {
		SecurityContextHolder.clearContext(); // 退出的接口是 /logout 时，可以不用调用，已经做了配置。
		return "Logout success";
	}
	
	@GetMapping("/normal")
	public String normal() {
		return "every one";
	}
	
	// 测试自定义注解
	@GetMapping("/pt")
	@HasPermission("testPermission")
	public String testPermission() {
		return "pt, You had been granted";
	}

	// 测试spring注解
	@GetMapping("/p")
	@PreAuthorize("hasAuthority('testPermission')")
	public String testSpringPermission() {
		return "P, You had been granted";
	}
	
	// 测试spring注解
	@GetMapping("/r")
	@PreAuthorize("hasRole('testRole')")
	public String testSpringRole() {
		return "r, You had been granted";
	}
	
}
